const Router = require('koa-router')
const router = new Router()
const u = require('../api')
const pageSize = 20

router.get(['/yxdt/', '/yxdt/p:num/'], async (ctx) => {
  ctx.response.status = 200
  const pageNum = ctx.params.num ? ctx.params.num : 1
  const keyword = ctx.query.keyword || ''
  ctx.config.nav[2].checked = true
  ctx.config.title = `元翔动态_新闻中心_元翔职校${pageNum > 1 ? '_第'+ pageNum +'页' : ''}`
  ctx.config.description = '新闻中心，元翔动态，元翔职校'
  ctx.config.keyword = '元翔动态,新闻中心,元翔职校'
  ctx.config.banner = `${ctx.config.host}/imgs/banner3.jpg`

  let { errno, errmsg, result } = await u.getNewsList({
    category: '0',
    keyword,
    pageNum,
    pageSize
  })
  if (errno == 0) {
    result.list.forEach(item => {
      item.href = `${ctx.config.host}/yxdt/${item.id}.html`
      item.publishedTimeNow = item.publishedTime ? item.publishedTime.split(' ')[0] : ''
    })
  } else {
    ctx.redirect('/404.html') 
  }

  await ctx.render('xwzx.ejs', {
    config: ctx.config,
    menu: [{
      title: '元翔动态',
      pinyin: 'yxdt',
      checked: true
    }, {
      title: '行业动态',
      pinyin: 'hydt',
      checked: false
    }],
    list: result.list || [],
    pathname: 'yxdt',
    pageNum,
    pages: result.pages,
    keyword
  })
})

router.get(['/hydt/', '/hydt/p:num/'], async (ctx) => {
  ctx.response.status = 200
  const pageNum = ctx.params.num ? ctx.params.num : 1
  const keyword = ctx.query.keyword || ''
  ctx.config.nav[2].checked = true
  ctx.config.title = `行业动态_新闻中心_元翔职校${pageNum > 1 ? '_第'+ pageNum +'页' : ''}`
  ctx.config.description = '新闻中心，行业动态，元翔职校'
  ctx.config.keyword = '行业动态,新闻中心,元翔职校'
  ctx.config.banner = `${ctx.config.host}/imgs/banner3.jpg`

  let { errno, errmsg, result } = await u.getNewsList({
    category: '1',
    keyword,
    pageNum,
    pageSize
  })
  if (errno == 0) {
    result.list.forEach(item => {
      item.href = `${ctx.config.host}/hydt/${item.id}.html`
      item.publishedTimeNow = item.publishedTime ? item.publishedTime.split(' ')[0] : ''
    })
  }

  await ctx.render('xwzx.ejs', {
    config: ctx.config,
    menu: [{
      title: '元翔动态',
      pinyin: 'yxdt',
      checked: false
    }, {
      title: '行业动态',
      pinyin: 'hydt',
      checked: true
    }],
    list: result.list || [],
    pathname: 'hydt',
    pageNum,
    pages: result.pages,
    keyword
  })
})

module.exports = router